<?php
/**
 * @Name: Where.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace HugCode\PhpUnits\Frame\DB;

class Where
{

    /**
     * @Desc 参数生成where
     * @param array $params 请求参数
     * @param array $fieldList  条件字段
     * @param array $where  默认条件
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    public static function paramsCreateWhere(array $params, array $fieldList, array $where = []): array
    {
        foreach ($fieldList as $field => $operator) {
            if (isset($params[$field]) && $params[$field] !== '') {
                $value = $params[$field];
                if (is_array($operator)) {
                    list($operator, $prefix) = $operator;
                    if (!empty($prefix)) {
                        $field = $prefix . '.' . $field;
                    }
                }
                if ($operator == 'like') {
                    $value = "%" . $value . "%";
                }
                $operator = is_array($value) ? 'in' : $operator;
                $where[]  = [$field, $operator, $value];
            }
        }
        return $where;
    }

    /**
     * @Desc between 时间条件（时间戳转时间格式 Ymd
     * @param array $params  请求参数
     * @param string $field  条件字段
     * @param int $default   默认天数
     * @param array $where   默认条件
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    public static function paramsWhereBetweenDay(array $params, string $field, int $default = 0, array $where = []): array
    {
        $start_day = _array_field($params, 'start_time', 0);
        $end_day   = _array_field($params, 'end_time', 0);
        if (empty($start_day) && empty($end_day)) {
            if (empty($default)) return $where;
            $end_day   = time();
            $start_day = strtotime('-' . $default . ' day');
        }
        $start_day = date('Ymd', $start_day);
        $end_day   = date('Ymd', $end_day);
        if ($start_day == $end_day) {
            $where[] = [$field, '=', $start_day];
        } else {
            $where[] = [$field, 'between', [$start_day, $end_day]];
        }

        return $where;
    }

}
